package com.socket;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/29 9:47
 * @since JDK 1.8
 */
public class SocketClient {

    public static void main(String[] args) {
        Map<String, Object> stringObjectMap=new HashMap<>();
        stringObjectMap.put("class","com.socket.Test");
        stringObjectMap.put("methodName","TestOne");
        Map<String, Object> objectMap=(Map<String, Object>) Clinet(stringObjectMap,"127.0.0.1",6666);
        objectMap.forEach((k,v)->{
            System.out.println(k+":"+v);
        });
    }

    protected static Object Clinet(Map<String,Object> map,String ip,Integer port){
        Socket socket = null;
        ObjectOutputStream os = null;
        ObjectInputStream is = null;
        Map<String,Object> res;
        try {
            //String str="47.111.242.190";
            socket = new Socket(ip, port);
            os = new ObjectOutputStream(socket.getOutputStream());
            os.writeObject(map);
            os.flush();
            is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            res=(Map<String, Object>)is.readObject();
            // this.backup(map,res);
            return res;
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("连接超时");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        {
            try {
                is.close();
            } catch (Exception ex) {
            }
            try {
                os.close();
            } catch (Exception ex) {
            }
            try {
                socket.close();
            } catch (Exception ex) {
            }
        }
        return null;
    }
}
